
// page
var pageCodes = 0;
const CODE_UNREGISTRYED = 1;    // unregistry
const CODE_REGISTRYED = 2;      // registry
const CODE_CHANGE_PASSWORD = 3; // change password

function togglePageCode(pageCode = 0) {
    pageCodes = pageCode
    if (pageCode == CODE_UNREGISTRYED) {
        document.getElementById("changepw-area").style.display = "none";
        document.getElementById("login-area").style.display = "none";
        document.getElementById("init-area").style.display = "block";
    } else if (pageCode == CODE_REGISTRYED) {
        document.getElementById("changepw-area").style.display = "none";
        document.getElementById("init-area").style.display = "none";
        document.getElementById("login-area").style.display = "block";
    } else if (pageCode == CODE_CHANGE_PASSWORD) {
        document.getElementById("login-area").style.display = "none";
        document.getElementById("init-area").style.display = "none";
        document.getElementById("changepw-area").style.display = "block";
    } else {
        document.getElementById("login-area").style.display = "none";
        document.getElementById("init-area").style.display = "none";
        document.getElementById("changepw-area").style.display = "none";
    }
}

// ------------------------------------------------------------------
// user
var currentUser;
function getPageCodeByUser() {
    apis.getUser().then((user) => {
        console.log(user)
        if (user && user.secretKey) {
            currentUser = user;
            togglePageCode(CODE_REGISTRYED)
        } else {
            togglePageCode(CODE_UNREGISTRYED)
        }
    }).catch(e => {
        togglePageCode(0)
    })
}
getPageCodeByUser()

// ------------------------------------------------------------------
// datasource
configPromise.then(config => {
    fillDbPath(config.dbPath)
})

function fillDbPath(dbPath) {
    document.getElementById("datasource-text").innerHTML = dbPath
}


// ------------------------------------------------------------------
// login
function login() {
    const passwdEl = document.forms["login-form"].elements.password;
    const usernameEl = document.forms["login-form"].elements.username;

    getSecretKeyByPassword(currentUser.secretKey, passwdEl.value).then(() => {
        setUsername(usernameEl.value);
        userLogin(passwdEl.value)
        window.location.replace('./index.html');
    }).catch(e => {
        toast("Password Invalid")
    })
}
document.getElementById("btn-submit").addEventListener("click", e => {
    login()
})
function initUsername() {
    const usernameEl = document.forms["login-form"].elements.username;
    if (usernameEl) {
        usernameEl.value = getUsername()
    }
}
initUsername()

// ------------------------------------------------------------------
// change password
var changePasswordLoading = false;

function changePassword() {
    if (changePasswordLoading) return;
    const changepwForm = document.forms["changepw-form"]

    const oldPasswd = changepwForm.elements["oldPassword"].value;
    const newPasswd = changepwForm.elements["newPassword"].value;
    const newPasswd2 = changepwForm.elements["newPassword2"].value;

    if (!oldPasswd || !newPasswd || !newPasswd2) {
        toastError("OldPasswd And NewPasswd Is Required");
        return;
    }
    if (newPasswd !== newPasswd2) {
        toastError("Twice Paswordes Not Same");
        return;
    }

    setChagnePasswordLoading(true);
    getSecretKeyByPassword(currentUser.secretKey, oldPasswd).then((originSecretKey) => {
        encryptor.encrypt(originSecretKey, newPasswd).then((newSecretKey) => {
            apis.updateUser({ 
                username: getUsername(),
                secretKey: newSecretKey 
            }).then(() => {
                setChagnePasswordLoading(false);
                userLogin(newPasswd)
                window.location.replace('./index.html');
            }).catch((e) => {
                setChagnePasswordLoading(false);
            })
        })
    }).catch((e) => {
        setChagnePasswordLoading(false);
    })
}
document.getElementById("btn-changepwd").addEventListener("click", e => {
    changePassword()
})
function setChagnePasswordLoading(flag = true) {
    if (flag) {
        changePasswordLoading = true;
        document.getElementById("btn-changepwd").classList.add("loading");
    } else {
        changePasswordLoading = false;
        document.getElementById("btn-changepwd").classList.remove("loading");
    }
}


// ------------------------------------------------------------------
// init password
document.getElementById("btn-init").addEventListener("click", () => {
    var initForm = document.getElementById("init-form")
    var password = initForm.elements.password.value;
    var password2 = initForm.elements.password2.value;
    if (!password || password != password2) {
        toastError("Two passwords are inconsistent")
        return
    }

    initPassword(password).then(encrypted => {
        apis.updateUser({
            secretKey: encrypted
        }).then(() => {
            userLogin(password)
            window.location.replace('./index.html');
        }).catch(e => {
            toastError(e.message)
        })
    })
})

function initPassword(password) {
    var secretKey = encryptor.getRandomKey();
    return encryptor.encrypt(secretKey, password)
}


// ------------------------------------------------------------------
// keydown
document.body.addEventListener("keydown", e => {
    if (e.key.toLowerCase() == "enter") {
        if (pageCodes == CODE_REGISTRYED) {
            login()
        } else if (pageCodes == CODE_CHANGE_PASSWORD) {
            changePassword()
        } else if (pageCodes == CODE_UNREGISTRYED) {
            document.getElementById("btn-init").click()
        }
    }
})